package com.ofps.forms.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ofps.forms.common.utils.R;
import com.ofps.forms.domain.Option;
import com.ofps.forms.service.OptionService;
import com.ofps.forms.service.QuestionCheckboxService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.ofps.forms.mapper.AnswerCheckboxMapper;
import com.ofps.forms.domain.AnswerCheckbox;
import com.ofps.forms.service.AnswerCheckboxService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.ofps.common.utils.SecurityUtils.getUserId;


@Service
public class AnswerCheckboxServiceImpl extends ServiceImpl<AnswerCheckboxMapper, AnswerCheckbox> implements AnswerCheckboxService {
    @Resource
    private AnswerCheckboxMapper answerCheckboxMapper;
    //    @Autowired
//    AnswerCheckboxServiceImpl answerCheckboxService;
    @Autowired
    QuestionCheckboxService questionCheckboxService;
    @Autowired
    OptionService optionService;

    @Override
    public R delete(Map<String, Object> body) {
        QueryWrapper<AnswerCheckbox> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id", body.get("id"));
        return answerCheckboxMapper.delete(queryWrapper) == 1 ? R.ok("删除成功") : R.error("删除失败");
    }

    @Override
    public R save(HttpServletRequest request, Map<String, Object> body) {
        if (body == null || !body.containsKey("optionId"))
            return R.error("参数错误");

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


        String id = (String) body.get("id");//答案表id
        Integer userId = (Integer) body.get("userId");
//        Integer userId = TokenUtil.getId(request);
//        Integer userId = Math.toIntExact(getUserId());
        String formId = (String) body.get("formId");
        String questionId = (String) body.get("questionId");
        Boolean isSubmit = (Boolean) (body.get("isSubmit"));
        String recordId = (String) body.get("recordId");
        String flowInstId = (String) body.get("flowInstId");
        Date createTime;
        try {
            createTime = sdf.parse(body.get("createTime").toString());
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
        //获取optionId数组
        List<String> optionId = (List<String>) body.get("optionId");
        //创建多选数组
        Collection<AnswerCheckbox> answerCheckboxEntities = new LinkedList<>();

        optionId.forEach(option ->
                answerCheckboxEntities.add(
                        new AnswerCheckbox().setId(id)
                                .setUserId(userId)
                                .setFormId(formId)
                                .setQuestionId(questionId)
                                .setOptionId(option)
                                .setCreateTime(createTime)
                                .setIsSubmit(isSubmit)
                                .setRecordId(recordId)
                                .setFlowInstId(flowInstId)
                )
        );

        //存在id
        if (answerCheckboxMapper.exists(new QueryWrapper<AnswerCheckbox>().eq("id", id))) {
            answerCheckboxMapper.delete(new QueryWrapper<AnswerCheckbox>().eq("id", id));
        }
        return this.saveBatch(answerCheckboxEntities) ? R.ok("保存多选题答案成功！") : R.error("保存多选题答案失败！");


    }

    @Override
    public List<AnswerCheckbox> queryCheckboxWithFormId(String formId) {
        QueryWrapper<AnswerCheckbox> answerCheckboxDaoQueryWrapper = new QueryWrapper<>();
        answerCheckboxDaoQueryWrapper.eq("form_id", formId);
        List<AnswerCheckbox> answerCheckboxList = answerCheckboxMapper.selectList(answerCheckboxDaoQueryWrapper);
        return answerCheckboxList;
    }

    @Override
    public List<AnswerCheckbox> queryCheckboxWithQuestionId(String QuestionId) {
        QueryWrapper<AnswerCheckbox> answerCheckboxDaoQueryWrapper = new QueryWrapper<>();
        answerCheckboxDaoQueryWrapper.eq("question_id", QuestionId);
        List<AnswerCheckbox> answerCheckboxList = answerCheckboxMapper.selectList(answerCheckboxDaoQueryWrapper);
        return answerCheckboxList;
    }

    @Override
    public Map<String, Object> summerizeCheckboxMessage(Map<String,Object>body) {
        List<AnswerCheckbox> checkboxEntityList = new ArrayList<>();
        checkboxEntityList = queryCheckboxWithQuestionId(body.get("question_id").toString());
        //查询到的checkbox列表
        Map<String , Object> summerizeMessages = new HashMap<>();
        Map <String,Map>TempSummerizeMessage = new HashMap<>();
        //汇总信息的列表
        Integer sum = 0;
        //计算所有的选择次数（用于计算百分比）
        List<Option> optionEntityList= optionService.queryWithId(body);
        sortByOrderId(optionEntityList,0,optionEntityList.size()-1);
        //System.out.println(optionEntityList);
        //获取选项信息
        List<String> Message = new ArrayList<>();
        for(Option optionEntity : optionEntityList){
            Message.add(optionEntity.getOrderId().toString());
            if (optionEntity.getContent().isEmpty() == false)
                Message.add(optionEntity.getContent());
            else
                Message.add("null");
            Message.add("0");
            Message.add("0");
        }
        System.out.println(Message);
        for(AnswerCheckbox answerCheckboxEntity : checkboxEntityList){
            Integer num = Integer.parseInt(answerCheckboxEntity.getOptionId().toString());
            //System.out.println("num:"+num.toString());
            Integer index = (num - 1)*4 + 2;
            Integer newVal = Integer.parseInt(Message.get(index).toString()) + 1;
            Message.set(index,newVal.toString());
            sum++;
        }

        for (Integer i = 1;i<checkboxEntityList.size() / 4;i++){
            Integer index = (i - 1)*4 + 2;
            Integer num = Integer.parseInt(Message.get(index).toString());
            Float target = (num.floatValue()/sum.floatValue())*100;
            String Target = String.format("%.2f",target).toString() + "%";
            Message.set(index+1,Target);
        }
        List<Map> structMessage = new ArrayList<>();

        for(int i = 0; i < Message.size() / 4 ; i++){
            Map<String,String> struct = new HashMap<>();
            struct.put("order_id",Message.get(i * 4 + 0));
            struct.put("order_information",Message.get(i * 4 + 1));
            struct.put("number",Message.get(i * 4 + 2));
            struct.put("percentage",Message.get(i * 4 + 3));
//            for(int j = 0; j < 4 ; j++){
//                struct.add(Message.get(i * 4 + j));
//            }
            structMessage.add(struct);
        }
//        List<String> Messages = new ArrayList<>();
//               for( AnswerCheckboxEntity answerCheckboxEntity : checkboxEntityList){
//           String id = answerCheckboxEntity.getOptionId();
//           Map<String,Object> message = new HashMap<>();
//           if(TempSummerizeMessage.containsKey(id)!=true)
//               TempSummerizeMessage.put(id,message);
//           if(TempSummerizeMessage.get(id).containsKey("select_num") != true){
//               TempSummerizeMessage.get(id).put("select_num",1);
//           }
//           else{
//               TempSummerizeMessage.get(id).put("select_num",Integer.parseInt(TempSummerizeMessage.get(id).get("select_num").toString())+1);
//           }
//           sum++;
//       }
//        for(AnswerCheckboxEntity answerCheckboxEntity : checkboxEntityList){
//            String index = answerCheckboxEntity.getOptionId();
//            if(Messages.contains(index) == false){
//                Messages.add(index);
//                Messages.add("1");
//                Messages.add(optionService.queryWithOptionId(index,body.get("question_id").toString()).getContent().toString());
//            }
//            else{
//                System.out.println("Messages");
//                System.out.println(Messages);
//                System.out.println(index);
//                Integer OrderIdIndex = searchList(Messages,index);
//                Integer newVal = Integer.parseInt(Messages.get(OrderIdIndex))+1;
////                数值+1
//                Messages.set(OrderIdIndex+1,newVal.toString());
//            }
//            sum++;
//        }

//        summerizeMessages.put("summerizeCheckBox",Messages);




//       for(String key : summerizeMessages.keySet()){
//           Integer num = Integer.parseInt(summerizeMessages.get(key).get("select_num").toString());
//           Float percent = num.floatValue() / sum.floatValue()*100;
//           summerizeMessages.get(key).put("percentage",percent.toString()+"%");
//       }
//
//
//        //System.out.println(optionEntityList.size());
//
//            //summerizeCheckbox.get(key).put()
//       Map<String,Integer> Message = new HashMap<>();
        summerizeMessages.put("sum",sum);
        summerizeMessages.put("type",2);
        summerizeMessages.put("total_message",structMessage);
        return summerizeMessages;
    }
    private  Integer searchList(List<String> list , String target){
        Integer index = 0;
        for (Integer i = 0 ; i < list.size(); i++){
            String str = list.get(i);
            if (target.equals(str)){
                index = i;
                break;
            }
            index = -1;
        }
        return index;
    }
    private  void sortByOrderId(List<Option> list,Integer start,Integer end){
        if (start >= end) {
            return;
        }
        Option a =list.get(start);//定义基准值
        int i = start;//开始位置下标
        int j = end;//末尾位置下标
        while (i < j) {
            while (i<j && Integer.parseInt(list.get(j).getOrderId().toString())>=a.getOrderId()) {
                j--;
            }
            while (i<j && Integer.parseInt(list.get(i).getOrderId().toString())<=a.getOrderId()) {
                i++;
            }
            if (i<j) {//交换i和j的值
                Collections.swap(list,i,j);
//                int temp = arr[j];
//                arr[j] = arr[i];
//                arr[i] = temp;
            }
        }
        list.set(start,list.get(i));
        list.set(i,a);
        sortByOrderId(list, start, i-1);//递归调用
        sortByOrderId(list, i+1, end);
    }
}
